package com.audaque.springboot.foshanupload.web.httpclientdemo.ieg.staticfile;

import cn.hutool.http.HttpRequest;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.audaque.springboot.foshanupload.web.exception.RException;
import com.audaque.springboot.foshanupload.web.httpclientdemo.ieg.staticfile.model.IegStaticFileInsertDto;
import com.audaque.springboot.foshanupload.web.httpclientdemo.ieg.staticfile.model.IegStaticFileInsertVo;
import com.audaque.springboot.foshanupload.web.httpclientdemo.ieg.token.IegTokenProvider;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

@Slf4j
@Component
public class IegStaticFileProvider {

    @Autowired
    private IegStaticFileProperties iegStaticFileProperties;

    @Autowired
    private IegTokenProvider iegTokenProvider;


    @Autowired
    private IegS3Properties iegS3Properties;


    @Autowired
    private ObjectMapper objectMapper;

    public String insert(IegStaticFileInsertDto req, String coverUrl, String fileType) throws Exception {
        //每次插入新图片，不做更新
        IegStaticFileInsertVo iegStaticFileInsertVo = insert(req, false);
        String preSignedUrl = iegStaticFileInsertVo.getPreSignedUrl();
        String thumbnailPreSignedUrl = iegStaticFileInsertVo.getThumbnailPreSignedUrl();
        byte[] bytes = url2img2bytes(coverUrl);
        if(bytes==null){
            throw new RException("读取不到图片字节数组");
        }
        //只做上传，不做更新
        upload(bytes, preSignedUrl, fileType);
        upload(bytes, thumbnailPreSignedUrl, fileType);
        return iegStaticFileInsertVo.getUrl();
    }

    private IegStaticFileInsertVo insert(IegStaticFileInsertDto req, Boolean retryedYn) throws Exception {
        String tokenKey = iegStaticFileProperties.getTokenKey();
        String url = iegStaticFileProperties.getInsertUrl();
        String v2Token = iegTokenProvider.getV2Token();
        String body = objectMapper.writeValueAsString(req);
        log.debug("ieg创建静态文件接口 1000086 调用中");
        String result = null;
        try {
            result = HttpRequest.post(url)
                    .header(tokenKey, v2Token).body(body)
                    .execute().body();
        } catch (Exception e) {
            throw new RException("ieg创建静态文件接口 调用过程中异常 1000086 %s",e.getMessage());
        }
        if (StringUtils.isBlank(result)) {
            throw new RException("ieg创建静态文件接口 响应异常 1000086 无响应");
        }
        log.debug("ieg创建静态文件接口 1000086 result {}" ,result);
        IegStaticFileInsertVo rsp = null;
        try {
            rsp = (IegStaticFileInsertVo) objectMapper.readerFor(IegStaticFileInsertVo.class).readValue(result);
        } catch (Exception e) {
            throw new RException("ieg创建静态文件接口 反序列化异常 1000086 %s", e.getMessage());
        }
        if (rsp!=null&&rsp.getCode() != null) {
            if (!retryedYn && !iegTokenProvider.authorize(v2Token)) {
                iegTokenProvider.setV2Token(null);
                insert(req, true);
            }
            throw new RException("ieg创建静态文件接口 响应异常 1000086 %s", rsp.getMsg());
        }
        return rsp;

    }


    private void upload(byte[] req, String url, String fileType) {
        log.debug("ieg上传静态文件接口 1000086 调用中");
        String result = null;
        try {
            result = HttpRequest.put(url)
                    .contentType("image/" + fileType)
                    .header(iegS3Properties.getAclHeaderKey(), iegS3Properties.getAclHeaderValue())
                    .body(req).execute().body();
        } catch (Exception e) {
            throw new RException("ieg上传静态文件接口 调用过程中异常 1000086 %s",e.getMessage());
        }
        if (StringUtils.isNotBlank(result)) {
            throw new RException("ieg上传静态文件接口 响应异常 1000086");
        }
        log.debug("ieg上传静态文件接口 1000086 result {}" ,result);
    }

    /**
     * 根据url获取图片字节数组
     */
    private byte[] url2img2bytes(String url) {
        InputStream fis = null;
        try {
            URL getUrl = new URL(url);
            URLConnection connection = getUrl.openConnection();
            connection.setRequestProperty("Referer", "");
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36");
            connection.setDoOutput(true);
            fis = connection.getInputStream();
            if(fis==null){
                return null;
            }
            return FileCopyUtils.copyToByteArray(fis);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


}
